package com.yang.simple_rpc.client.net.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

/**
 *  Netty发送和接受数据的handler处理类，定义Netty入站处理细则
 * Java的NIO到Netty的channel
 * @author : morikawaaaa
 * @date : 2022
 */
public class SendHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(SendHandler.class);
    private CountDownLatch cdl;
    private Object readMsg = null;
    private byte[] bytes;

    public SendHandler(byte[] bytes){
        cdl = new CountDownLatch(1);
        this.bytes = bytes;
    }

    //连接服务器成功后，请求发送数据
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("Success connect to server : {}", ctx);
        ByteBuf reqBuf = Unpooled.buffer(bytes.length);
        reqBuf.writeBytes(bytes);
        logger.info("Client sends message : {}", reqBuf);
        ctx.writeAndFlush(reqBuf);
    }

    //读取数据，cdl-1唤醒await
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        logger.info("Client reads message : {}", msg);
        ByteBuf msgBuf = (ByteBuf) msg;
        byte[] resp = new byte[msgBuf.readableBytes()];
        msgBuf.readBytes(resp);
        readMsg = resp;
        cdl.countDown();
    }

    //等待数据读取完成
    public Object rspData() throws InterruptedException{
        cdl.await();
        return readMsg;
    }

    //读取完成需要刷新数据
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        ctx.flush();
    }

    //捕获异常并关闭连接
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        cause.printStackTrace();
        logger.error("Exception occured : {}", cause.getMessage());
        ctx.close();
    }

}
